var versionUploadJs = function(targetObj) {
	this.targetObj = targetObj;
	this.arr_md5 = [];					//加载页面时，将已上传成功的分片数组化
	this.chunks = 0;					//分片总数量，用来上传成功以后校验分片文件总数
	this.repart_chunks = 0;
	this.upload_success = false;
	this.isResetUp = false;
	this.times = 0;
	this.interval = 0;
	this.tokenid = this.randomWord(false, 32);
	this.createWebUpload();
	return this;
}
versionUploadJs.prototype = {

		/**
		 * 创建上传组建
		 */
		createWebUpload : function() {
			var that = this;
			//注册组件
			WebUploader.Uploader.register({
				'before-send': 'preupload'
			}, {
				preupload: function( block ) {
					var me = this,
					owner = this.owner,
					deferred = WebUploader.Deferred();
					that.chunks = block.chunks;
					//及时显示进度
					owner.md5File(block.blob).progress(function(percentage) {
						console.log('Percentage:', percentage);
					})
					//如果读取出错了，则通过reject告诉webuploader文件上传出错。
					.fail(function() {
						deferred.reject();
						console.log("==1==");
					})
					//md5值计算完成
					.then(function( md5 ) {
						if(that.arr_md5.contains(md5)){//数组中包含+(block.chunk+1)
							deferred.reject();
							console.log("分片已上传"+block.file.id);
						}else{
							deferred.resolve();
							console.log("开始上传分片："+md5);
						}
					});
					return deferred.promise();
				}
			});
			//初始化WebUploader
			that.uploader = WebUploader.create({
				//swf文件路径
				swf: 'js/utils/Uploader.swf',
				//文件接收服务端。
				server: baseApiPath + 'largeFileUpoad/fileupload?tokenid=' + that.tokenid,
				//选择文件的按钮，可选。内部根据当前运行是创建，可能是input元素，也可能是flash.
				pick: that.targetObj.find("#uploadBtn"),
				method:'POST',
				//是否分片
				chunked :true,
				//分片大小
				chunkSize :1024*1024*4,
				chunkRetry :3,
				threads :10,//最大并发
				fileNumLimit :1,
				disableGlobalDnd: true,  //关掉全局拖拽
				duplicate :true,
				accept: {
					title: 'file',
					extensions: 'zip,rar',
					mimeTypes: '*/*'
				}
			});
			//注册各种事件
			this.registerEvent();
			//添加开始上传按钮事件
			this.targetObj.find("#startUpload").bind("click",function(){
				that.uploader.options.formData = {
						dateFomart:new Date().pattern("yyyyMMddHHmmssSSS")
				};
				that.uploader.upload();
				that.targetObj.find("#startUpload").css("background","#949a9c")
				that.targetObj.find("#startUpload").attr("disabled","disabled");
				//改变传输图片
				var continuinglyBtn = that.targetObj.find("#continuinglyBtn");
				continuinglyBtn.find("i").removeClass("off");
				continuinglyBtn.find("i").addClass("on");
				continuinglyBtn.css("background","#949a9c");
			});
			//添加断点续传的事件
			this.targetObj.find("#continuinglyBtn").bind("click",function(e){
				var btn = $(e.target);
				var btn_i = btn.find("i");
				if(btn_i.length == 0){
					btn_i = btn;
					btn = btn_i.parent("a");
				}
				if("on" == btn_i.attr("class") || that.isResetUp == false){
					return;
				}
				//如果是暂停状态，那么点玩变成续传状态
				btn_i.removeClass("off");
				btn_i.addClass("on");
				btn.css("background","#949a9c");
				that.uploader.retry();  //开启重传
				that.isResetUp = false;
			});
		},
		/**
		 * 注册WebUploader事件
		 */
		registerEvent:function(){
			var that = this;
			//当文件被加入队列之前触发，此事件的handler返回值为false，则此文件不会被添加进入队列。
			that.uploader.on('beforeFileQueued',function(file){
				that.uploader.reset();
//				that.targetObj.find("#upSpeedDiv").css("display","none");
				that.targetObj.find("#upFileName").html("请选择上传文件");
				that.targetObj.find("#fileSize").html("0MB");
				that.targetObj.find("#startUpload").css("background","#00b7ee")
				that.targetObj.find("#startUpload").removeAttr("disabled");
				if(",zip,rar,".indexOf(","+file.ext+",")<0){
					notification({title :"提示", message : "只支持zip，rar文件格式"}, "info");
					return false;
				}
				if(file.name.indexOf("_") !=32){
					notification({title :"提示", message : "文件名格式不匹配，文件名格式如下：32位MD5校验码加下划线和版本号"}, "info");
					return false;
				}
				//每次只能上传一个文件，所以在选择文件时，先充值队列
				var maxFileSize = 1024*1024*1024*2;
				if(maxFileSize < file.size){
					notification({title :"提示", message : "最大值支持上传2GB的文件"}, "info");
					return false;
				}
				return true;
			});

			//当有文件添加进来的时候 
			that.uploader.on( 'fileQueued', function( file ) {
				that.times = 1;
				that.upload_success = false;
				//选中文件，填充界面
				that.targetObj.find("#upSpeed").html("0KB/S");
//				that.targetObj.find("#upSpeedDiv").css("display","block");
				that.targetObj.find("#upFileName").html(file.name);
				that.targetObj.find("#upFilePath").val("");
				that.targetObj.find("#fileSize").html((file.size/1024/1024).toFixed(2)+'MB');
				that.targetObj.find("#upFileProgress").css("width","0%");
				//文件开始上传后开始计时，计算实时上传速度
				that.interval = setInterval(function(){that.times++;},1000);

			});

			//上传过程中触发，携带上传进度。文件上传过程中创建进度条实时显示。  
			that.uploader.on( 'uploadProgress', function( file, percentage ) {  
				var status_pre = file.size*percentage-that.arr_md5.length*2*1024*1024;
				if(status_pre<=0){
					return;
				}
				that.targetObj.find("#upFileProgress").css("width",percentage * 100 + '%');
				var speed = ((status_pre/1024/1024)/that.times).toFixed(2);
				that.targetObj.find("#upSpeed").html(speed +"MB/S");
				if(percentage == 1){
					notification({title :"提示", message : "文件上传完成！！"}, "info");
				}
			}); 

			//文件上传成功时触发
			that.uploader.on( 'uploadSuccess', function( file,response) {
				var paramsData = {
						name:file.name,
						chunks:that.chunks,
						tokenid:that.tokenid
				};
				JsonpAjax(baseApiPath + 'largeFileUpoad/composeFile', JSON.stringify(paramsData), 'json', function(data) {
					that.upload_success = true;
					closeWindow(); //关闭窗口
					//查询版本信息
					ctVersionJs.loadHtml();

				});
			});

			//文件上传异常失败触发
			that.uploader.on( 'uploadError', function( file,reason ) {
				notification({title : '提示', message : "文件传输失败，请重传！！"}, 'info');
				//上传出错，把上传图片改为暂停图标
				that.isResetUp = true;
				var btn = that.targetObj.find("#continuinglyBtn");
				//如果是暂停状态，那么点玩变成续传状态
				btn.find("i").removeClass("on");
				btn.find("i").addClass("off");
				btn.css("background","#2590f1");
			});

			//某个文件开始上传前触发，一个文件只会触发一次。
			that.uploader.on( 'uploadStart', function(file) {
				console.info("file="+file.name);
				var paramsData = {
						name:file.name,
						tokenid:that.tokenid
				};
				//分片文件上传之前
				JsonpAjax(baseApiPath + 'largeFileUpoad/md5Validation', JSON.stringify(paramsData), 'json', function(data) {
					var md5_arr = data.results
					if(md5_arr != ""){
						that.arr_md5 = md5_arr.split(",")
					}else{
						that.arr_md5 = new Array();
					}
				});
			});

			//当所有文件上传结束时触发。
			that.uploader.on( 'uploadFinished', function() {

			});
		},


		/**
		 * 生成随机数
		 * @param randomFlag    是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
		 * @param min			最小长度
		 * @param max			最大长度
		 * @returns {String}    返回值
		 */
		randomWord:function(randomFlag, min, max){
			var str = "",
			range = min,
			arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

			// 随机产生
			if(randomFlag){
				range = Math.round(Math.random() * (max-min)) + min;
			}
			for(var i=0; i<range; i++){
				pos = Math.round(Math.random() * (arr.length-1));
				str += arr[pos];
			}
			return str;
		}
};